<template>
  <div class="margin-10">
    <el-card shadow="always" :body-style="{ padding: '20px' }">

      <el-steps :active="step" finish-status="success">
        <el-step title="基本信息" />
        <el-step title="指定用户" />
        <el-step title="指定用户标签" />
        <el-step title="指定用户分组" />
        <el-step title="选择商品" />
      </el-steps>
      <div v-show="step==1" class="common-content">
        <el-form ref="baseFormRef" :model="baseForm" :rules="baseFormRules" label-width="120px" size="mini">
          <el-row :gutter="20">
            <el-col :span="8" :offset="0">
              <el-form-item label="活动名称" prop="activity_name">
                <el-input v-model="baseForm.activity_name" />
              </el-form-item>
            </el-col>
            <el-col :span="8" :offset="0">
              <el-form-item label="活动状态" prop="status">
                <el-select v-model="baseForm.status" style="width:100%;" placeholder="活动状态" clearable>
                  <el-option
                    v-for="item in activityStatusList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8" :offset="0">
              <el-form-item label="选择地区" prop="address">
                <el-cascader
                  v-model="baseForm.address"
                  :options="addressList"
                  clearable
                  style="width:100%;"
                  :show-all-levels="true"
                  :props="{ expandTrigger: 'hover',emitPath:true, multiple: true, checkStrictly: true,label:'name',value:'id' }"
                />

              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="8" :offset="0">
              <el-form-item label="主图" prop="imageUrl">
                <logo-upload
                  :single-file="baseForm.imageUrl"
                  :show-file-list="false"
                  accept="image/jpeg, image/png"
                  style="width: 90px;height: 90px;"
                  @uploadCallback="baseFormMainImageSucc"
                />
              </el-form-item>
            </el-col>

            <el-col :span="8" :offset="0">
              <el-form-item label="时间段" prop="startEndTime">
                <el-date-picker
                  v-model="baseForm.startEndTime"
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                />
              </el-form-item>
            </el-col>

          </el-row>

          <el-row :gutter="20">
            <el-col :span="24" :offset="0">
              <el-form-item label="轮播图" prop="carousel">
                <logo-upload
                  :file-list="baseForm.carousel"
                  :show-file-list="true"
                  accept="image/jpeg, image/png"
                  @uploadCallback="carouselBack"
                />
              </el-form-item>
            </el-col>
          </el-row>

        </el-form>

      </div>
      <div v-show="step==2" class="common-content">
        <el-form ref="userActivityFormRef" :model="userActivityForm" :rules="userActivityFormRules" label-width="80px" size="mini">
          <el-row :gutter="20">
            <el-col :span="24" :offset="0">
              <el-form-item label="指定用户" prop="users">
                <el-table
                  ref="userMultipleTable"
                  v-loading="isLoadingUserList"
                  :data="userList"
                  border
                  stripe
                  :row-key="row=>row.id"
                  @selection-change="chooseUserChange"
                >
                  <el-table-column
                    fixed="left"
                    type="selection"
                    width="55"
                    align="center"
                    reserve-selection
                  />

                  <el-table-column
                    label="用户头像"
                    align="center"
                  >
                    <template slot-scope="scope">
                      <el-image :src="scope.row.avatar" fit="fill" :lazy="true" style="width:80px;height:80px;" />
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="id"
                    label="用户ID"
                    width="80"
                    align="center"
                  />
                  <el-table-column
                    prop="nickname"
                    label="姓名"
                    align="center"
                  />
                  <el-table-column
                    prop="mobile"
                    label="手机号"
                    align="center"
                  />
                  <el-table-column
                    prop="group_name"
                    label="分组名称"
                    align="center"
                  />
                  <el-table-column
                    prop="level_name"
                    label="等级"
                    align="center"
                  />
                  <el-table-column
                    prop="birthday"
                    label="生日"
                    align="center"
                  />
                </el-table>
                <el-pagination
                  style="margin-top:10px;"
                  :current-page.sync="paginationObj.start"
                  :page-sizes="paginationObj.pageSizes"
                  :page-size="paginationObj.limit"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="paginationObj.total"
                  background
                  @size-change="userSizeChange"
                  @current-change="userCurrentChange"
                />

              </el-form-item>
            </el-col>

          </el-row>

        </el-form>
      </div>
      <div v-show="step==3" class="common-content">
        <el-card>
          <div class="Label">
            <div class="leftLabel">
              <div class="each" :class="searchTagForm.category_id == '' ? 'isEach' : ''" @click="tagCategoryWay()">全部</div>
              <div
                v-for="item, index in tagCategoryList"
                :key="index"
                :class="searchTagForm.category_id == item.id ? 'isEach' : ''"
                class="each"
                @click="tagCategoryWay(item.id)"
              >
                {{ item.category_name }}

              </div>
            </div>
            <div class="rightLabel">
              <el-row>
                <el-col>
                  <el-form ref="tagActivityFormRef" :model="tagActivityForm" :rules="tagActivityFormRules" label-width="80px" size="mini">
                    <el-form-item prop="tagList">
                      <el-table
                        v-loading="isTagloading"
                        :header-cell-style="{
                          'background-color': '#f3f8fe',
                          color: '#606266',
                          height: '50px',
                        }"
                        highlight-current-row
                        :data="TagList"
                        style="width: 100%"
                        :row-key="row=>row.id"
                        @selection-change="chooseTagChange"
                      >
                        <el-table-column
                          fixed="left"
                          type="selection"
                          width="55"
                          align="center"
                          reserve-selection=""
                        />
                        <el-table-column align="center" width="200" prop="id" label="ID" />
                        <el-table-column align="center" prop="tag_name" label="标签名称" />

                      </el-table>
                    </el-form-item>

                  </el-form>

                </el-col>
              </el-row>
              <el-row class="marginTop" style="text-align: right">
                <el-pagination
                  :current-page="searchTagForm.page"
                  :page-sizes="[10, 20, 30, 40]"
                  :page-size="searchTagForm.count"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="total"
                  @size-change="handleTagSizeChange"
                  @current-change="handleTagCurrentChange"
                />
              </el-row>
            </div>
          </div>
        </el-card>
      </div>
      <div v-show="step==4" class="common-content">
        <el-form ref="userGroupFormRef" :model="userGroupForm" :rules="userGroupFormRules" label-width="80px" size="mini">
          <el-row :gutter="20">
            <el-col :span="24" :offset="0">
              <el-form-item label="指定用户分组" prop="groupList">
                <el-table
                  ref="userGroupMultipleTable"
                  v-loading="isLoadingUserGroupList"
                  :data="userGroupList"
                  border
                  stripe
                  :row-key="row=>row.id"
                  @selection-change="chooseUserGroupChange"
                >
                  <el-table-column
                    fixed="left"
                    type="selection"
                    width="55"
                    align="center"
                    reserve-selection=""
                  />

                  <el-table-column
                    prop="id"
                    label="分组ID"
                    align="center"
                  />
                  <el-table-column
                    prop="name"
                    label="分组名称"
                    align="center"
                  />
                  <el-table-column
                    prop="created_at"
                    label="创建时间"
                    align="center"
                  />

                </el-table>
                <el-pagination
                  style="margin-top:10px;"
                  :current-page.sync="userGroupForm.page"
                  :page-sizes="[10,20,30,40]"
                  :page-size="userGroupForm.page"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="groupTotal"
                  background
                  @size-change="groupSizeChange"
                  @current-change="groupCurrentChange"
                />

              </el-form-item>
            </el-col>

          </el-row>

        </el-form>
      </div>
      <div v-show="step==5" class="common-content">
        <goods-list @myselectionchange="handleChooseGoodsChange" @savesku="handleSaveSku" />
      </div>

      <!-- <el-button @click="doCancelAddOrEditActivity">取消</el-button> -->
      <el-button v-if="step!=1" type="primary" @click="preStep">上一步</el-button>
      <el-button v-if="step!=5" type="primary" @click="nextStep">下一步</el-button>
      <el-button v-if="step==5" type="primary" @click="doAddOrEditActivity">确定</el-button>

    </el-card>

  </div>
</template>
<script>
import LogoUpload from '@/components/FileUpload'
import { getUserList, getRegionList, getTagList, gettagCategoryList, getgroupList } from '@/api/user/index'
import { add, detail } from '@/api/activity/index'
import mix from '@/mixins/index'
import GoodsList from './components/GoodsList.vue'
import { parseTime } from '@/utils/index'
export default {
  name: 'AddSeckillActivity',
  components: {
    LogoUpload,
    GoodsList
  },
  mixins: [mix],
  data() {
    const mainImageValidator = (rule, value, callback) => {
      if (this.baseForm.main_image === {}) {
        callback(new Error('请上传商品主图'))
      } else {
        callback()
      }
    }
    // 轮播图非必填
    // const carouselValidator = (rule, value, callback) => {
    //   if (this.baseForm.carousel.length === 0) {
    //     callback(new Error('请上传至少一张活动轮播图'))
    //   } else {
    //     callback()
    //   }
    // }
    const isChooseUser = (rule, value, callback) => {
      if (this.choosedUserList.length === 0) {
        callback('至少选择一个用户！')
      } else {
        callback()
      }
    }
    const isChooseTag = (rule, value, callback) => {
      if (this.choosedTagList.length === 0) {
        callback('至少选择一个标签！')
      } else {
        callback()
      }
    }
    const isChooseGroup = (rule, value, callback) => {
      if (this.choosedGroupList.length === 0) {
        callback('至少选择一个用户分组！')
      } else {
        callback()
      }
    }
    return {
      isLoadingSeckillDetail: false,
      activityId: '', // 被编辑的活动ID
      isLoadingUserList: false, // 是否加载用户列表
      step: 1, // 添加秒杀活动步骤
      activityStatusList: [
        {
          label: '结束',
          value: -1
        },
        {
          label: '开启',
          value: 1
        },
        {
          label: '关闭',
          value: 2
        },
        {
          label: '进行中',
          value: 3
        }

      ],
      baseForm: {
        imageUrl: {}, // 主图url
        carousel: [] // 轮播图
      },
      baseFormRules: {
        // type: [{ required: true, message: '活动类型必填', trigger: 'blur' }],
        activity_name: [{ required: true, message: '活动名称必填', trigger: 'blur' }],
        // start_time: [{ required: true, message: '开始时间', trigger: 'blur' }],
        // end_time: [{ required: true, message: '结束时间', trigger: 'blur' }],
        startEndTime: [{ required: true, message: '开始结束时间必填', trigger: 'blur' }],
        status: [{ required: true, message: '活动状态必填', trigger: 'blur' }],
        imageUrl: [{ required: true, validator: mainImageValidator, trigger: 'blur' }],
        // carousel: [{ required: true, validator: carouselValidator, trigger: 'blur' }],
        address: [{ required: true, message: '省市区必填', trigger: 'blur' }]
      },
      addressList: [], // 省市区
      // 第二页用户相关
      userSearchFrom: {}, // 搜索用户信息
      userActivityForm: {}, // 活动选择的用户信息
      userActivityFormRules: {
        users: [{ required: true, validator: isChooseUser }]
      },
      userList: [], // 用户列表
      choosedUserList: [], // 选中的用户
      // 第三页标签相关
      isTagloading: false,
      searchTagForm: {
        category_id: '',
        page: 1,
        count: 10
      },
      tagCategoryList: [],
      TagList: [],
      total: 0,
      choosedTagList: [], // 选中的tag
      tagActivityForm: {},
      tagActivityFormRules: {
        tagList: [{ required: true, validator: isChooseTag }]
      },
      // 第四页数据
      userGroupForm: {
        page: 1,
        count: 10
      },
      userGroupFormRules: {
        groupList: [{ required: true, validator: isChooseGroup }]
      },
      userGroupList: [],
      groupTotal: 0,
      isLoadingUserGroupList: false,
      choosedGroupList: [],
      // 第五页数据
      choosedGoodsList: [],
      choosedSeckillGoodsSkuList: [] // 选中的秒杀商品规格列表
    }
  },
  created() {
    this.getRegionListData()
    this.getUserListData()
    // this.getAllTagAndCategory()
    this.getTagListWay()
    this.gettagCategoryListWay()
    this.getUserGroupList()
    this.activityId = this.$route.query.id
    if (this.activityId) {
      // 获取活动详情
      this.getSeckillActivityDetail()
    }
  },
  methods: {
    // 获取城市信息
    async getRegionListData() {
      const res = await getRegionList()
      const { code, data, message } = res
      if (code === 200) {
        this.addressList = data
      } else {
        this.$message.error(message)
      }
    },
    // 获取用户列表
    async getUserListData() {
      this.isLoadingUserList = true
      this.userSearchFrom.page = this.paginationObj.start
      this.userSearchFrom.count = this.paginationObj.limit
      const res = await getUserList(this.userSearchFrom)
      const { code, data, msg } = res
      if (code === 200) {
        this.userList = data.list
        this.paginationObj.total = data.total
      } else {
        this.$message.error(msg)
      }
      this.isLoadingUserList = false
    },
    // 主图上传成功
    baseFormMainImageSucc(res) {
      console.log('res==>', res)
      this.baseForm.imageUrl = res
      this.baseForm.image = {
        url: res.url,
        link_url: ''
      }
    },
    // 轮播图上传成功的回调
    carouselBack(res) {
      this.baseForm.carousel = res
    },
    // **************第二页**************
    // 选择用户发生改变
    chooseUserChange(val) {
      // console.log('val==>', val)
      this.choosedUserList = val
    },
    // 用户列表页面大小发生改变
    userSizeChange(val) {
      this.paginationObj.start = 1
      this.paginationObj.limit = val
      this.getUserListData()
    },
    // 用户列表当前页码发生改变
    userCurrentChange(val) {
      this.paginationObj.start = val
      this.getUserListData()
    },
    // **************第三页**************
    getTagListWay() {
      this.isTagloading = true
      getTagList(this.searchTagForm).then((res) => {
        this.isTagloading = false
        if (res.code !== 200) {
          this.$messages.error(res.msg)
          return
        }
        this.TagList = res.data.list
        this.total = res.data.total
      })
    },
    gettagCategoryListWay() {
      gettagCategoryList().then((res) => {
        if (res.code !== 200) {
          this.$messages.error(res.msg)
          return
        }
        this.tagCategoryList = res.data.list
      })
    },
    // 切换分类
    tagCategoryWay(id) {
      console.log('id==>', id)
      if (!id) {
        this.searchTagForm.category_id = ''
      } else {
        console.log('this.searchTagForm.category_id==>', id)
        this.searchTagForm.category_id = id
      }
      this.searchTagForm.page = 1
      this.getTagListWay()
    },
    chooseTagChange(res) {
      this.choosedTagList = res
    },
    handleTagSizeChange(val) {
      this.searchTagForm.count = val
      this.getTagListWay()
    },
    handleTagCurrentChange(val) {
      this.searchTagForm.page = val
      this.getTagListWay()
    },
    // **************第四页**************
    async getUserGroupList() {
      this.isLoadingUserGroupList = true
      const res = await getgroupList(this.userGroupForm)
      const { code, data, msg } = res
      if (code === 200) {
        this.userGroupList = data.list
        this.groupTotal = data.total
      } else {
        this.$message.error(msg)
      }
      this.isLoadingUserGroupList = false
    },
    chooseUserGroupChange(res) {
      this.choosedGroupList = res
    },
    groupSizeChange(val) {
      this.userGroupForm.count = val
      this.userGroupForm.page = 1
      this.getUserGroupList()
    },
    groupCurrentChange(val) {
      this.userGroupForm.page = val
      this.getUserGroupList()
    },

    // **************第五页**************
    handleChooseGoodsChange(res) {
      // console.log('res===>', res)
      this.choosedGoodsList = res
    },
    handleSaveSku(res) {
      // console.log('res==>', res)
      this.choosedSeckillGoodsSkuList = res
    },
    // **************最后操作**************
    // 取消添加或者编辑秒杀活动
    doCancelAddOrEditActivity() {
      this.isShowDialog = false
      this.baseForm = this.$options.data().baseForm
    },
    // 添加或者编辑秒杀活动
    async doAddOrEditActivity() {
      // 开始规整数据
      const paramsObj = {
        status: this.baseForm.status,
        activity_name: this.baseForm.activity_name,
        image: JSON.stringify(this.baseForm.image),
        start_time: parseTime(this.baseForm.startEndTime[0]),
        end_time: parseTime(this.baseForm.startEndTime[1]),
        images: JSON.stringify(this.baseForm.carousel.map(item => ({ url: item.url, link_url: '' }))),
        cover_region_json: JSON.stringify(this.baseForm.address),
        cover_user: this.choosedUserList.map(item => item.id).join(','),
        cover_label: this.choosedTagList.map(item => item.id).join(','),
        cover_group: this.choosedGroupList.map(item => item.id).join(','),
        seckill: this.choosedSeckillGoodsSkuList
      }
      // console.log('paramsObj===>', paramsObj)
      const res = await add(paramsObj)
      const { code, msg } = res
      if (code === 200) {
        this.$message.success('秒杀活动添加成功！')
      } else {
        this.$message.error(msg)
      }
    },
    preStep() {
      this.step--
    },
    nextStep() {
      // 验证第一个表单
      if (this.step === 1) {
        // if (this.validateForm('baseFormRef'))
        this.step++
      } else if (this.step === 2) {
        if (this.validateForm('userActivityFormRef')) this.step++
      } else if (this.step === 3) {
        if (this.validateForm('tagActivityFormRef')) this.step++
      } else if (this.step === 4) {
        if (this.validateForm('userGroupFormRef')) this.step++
      }
    },
    validateForm(form) {
      let result = true
      // 验证第一个表单
      this.$refs[form].validate((valid) => {
        if (valid) {
          result = result && true
        } else {
          result = result && false
        }
      })
      return result
    },
    // **************编辑************** detail
    async getSeckillActivityDetail() {
      const res = await detail({ id: this.activityId })
      const { code, data, msg } = res
      if (code === 200) {
        this.baseForm.activity_name = data.activity_name
        this.baseForm.address = JSON.parse(data.cover_region_json)
        this.baseForm.startEndTime = [new Date(data.start_time), new Date(data.end_time)]
        this.baseForm.imageUrl = { url: JSON.parse(data.image).url }
        this.baseForm.carousel = JSON.parse(data.images).map(item => ({
          url: item.url
        }))
        this.baseForm.status = data.status
        // this.getChooseUserList(data.cover_user.split(','))
        const coverUserIdArr = data.cover_user.split(',')

        this.userList.forEach(item => {
          if (coverUserIdArr.includes(String(item.id))) {
            this.choosedUserList.push(item)
          }
        })
        // 回显
        this.$nextTick(() => {
          this.choosedUserList.forEach(item => {
            this.$refs.userMultipleTable.toggleRowSelection(item, true)
          })
        })
      } else {
        this.$message.error(msg)
      }
    }
    // getChooseUserList(userIdList) {
    //   this.choosedUserList = []
    //   this.userSearchFrom.page = 1
    //   this.userSearchFrom.count = 10
    //   this.userSearchFrom.search_type = 2
    //   userIdList.forEach(async id => {
    //     this.userSearchFrom.search_name = id
    //     const res = await getUserList(this.userSearchFrom)
    //     const { code, data, msg } = res
    //     if (code === 200) {
    //       this.choosedUserList.push(...data.list)
    //       console.log('this.choosedUserList===>', this.choosedUserList)
    //     } else {
    //       this.$message.error(msg)
    //     }
    //   })
    // }

  }
}
</script>
<style lang='scss' scoped>
.margin-10{
  margin: 10px;
  .el-steps{
    padding: 10px 50px 50px;
  }
    .Label {
    display: flex;
  }

  .leftLabel {
    min-width: 200px;
    max-height: 80vh;
    min-height: 60vh;
    display: inline-block;

    .each {
      padding: 0 20px;
      height: 50px;
      line-height: 50px;
      cursor: pointer;
      font-size: 14px;

      .right {
        transition: .3s;
        display: none;
        float: right;
        font-size: 700;
      }
    }

    .each:hover {
      .right {
        display: inline-block;
      }
    }

    .isEach {
      position: relative;
      background-color: #eff6fe;
      color: #2d8cf0;

    }

    .isEach::after {
      content: "";
      position: absolute;
      height: 100%;
      width: 2px;
      background-color: #2d8cf0;
      top: 0px;
      right: 0px;
    }
  }
  .rightLabel {
    flex: 1;
    border-left: 1px solid #ededed;
    padding: 20px;
  }
}
</style>
